using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace BlockOS.Client
{
    public class ServerListItem : MonoBehaviour, IPointerClickHandler
    {
        private const int MAX_DISPLAY_LATENCY_VALUE = 999;

        public Graphic background;
        public Color normalBgColor;
        public Color selectedBgColor;

        [Space]
        public TMP_Text title;
        public TMP_Text description;
        public Image latencyImage;
        public TMP_Text latencyValue;
        public Button editButton;
        public Button deleteButton;

        [Space]
        private bool m_IsSelected;
        public bool IsSelected
        {
            get => m_IsSelected;
            set
            {
                m_IsSelected = value;
                if (m_IsSelected)
                {
                    background.color = selectedBgColor;
                }
                else
                {
                    background.color = normalBgColor;
                }
            }
        }

        public Action onSelect;
        public Action onChoose;

        [SerializeField]
        private Sprite[] latencyStrength;

        private void OnDestroy()
        {
            deleteButton.onClick.RemoveAllListeners();
            onSelect = null;
            onChoose = null;
        }

        public void SetTitle(string title)
        {
            this.title.text = title;
        }

        public void SetDescription(string description)
        {
            this.description.text = description;
        }

        public void SetLatency(int ms)
        {
            ms = Mathf.Clamp(ms, 0, MAX_DISPLAY_LATENCY_VALUE);
            var idx = Mathf.FloorToInt((float)ms * latencyStrength.Length / MAX_DISPLAY_LATENCY_VALUE);
            latencyImage.sprite = latencyStrength[idx];
            latencyValue.text = $"{ms} ms";
        }

        public void OnPointerClick(PointerEventData eventData)
        {
            if (!IsSelected)
            {
                onSelect?.Invoke();
                IsSelected = true;
            }
            else
            {
                onChoose?.Invoke();
                //GameClient.Instance.ShowToast(title.text);
            }
        }
    }
}
